import React from 'react';
import ReactDom from 'react-dom';

export interface IModalHigherOrderFunctionProps {
    /**
     * @param 移除Node回调
     */
    onModalClose?: (otherParams?: any) => void;
}

interface IReturnModal<T> {
    oDiv: HTMLDivElement | null;
    open: (props: T) => void;
    close: () => void;
}

/**
 * @see 包装组件 通过<ReactDom.render> 注入组件 并提供 open和close方法
 **/
function ModalHigherOrderFunction<T extends IModalHigherOrderFunctionProps>(
    WrappendComponent: React.FC<any>
): IReturnModal<T> {
    return {
        oDiv: null,
        open: function (props: T) {
            this.close();
            this.oDiv = document.createElement('div');
            document.body.appendChild(this.oDiv);
            ReactDom.render(
                <WrappendComponent
                    {...props}
                    onModalClose={(otherParams?: any) => {
                        if (typeof props.onModalClose === 'function') {
                            props.onModalClose(otherParams);
                        }
                        if (this.oDiv) {
                            ReactDom.unmountComponentAtNode(this.oDiv);
                        }
                        if (this.oDiv?.parentNode) {
                            this.oDiv.parentNode.removeChild(this.oDiv);
                        }
                    }}
                />,
                this.oDiv
            );
        },
        close: function () {
            try {
                if (this.oDiv) {
                    ReactDom.unmountComponentAtNode(this.oDiv);
                }
                if (this.oDiv?.parentNode) {
                    this.oDiv.parentNode.removeChild(this.oDiv);
                }
            } catch (error) {
                console.log('ModalHigherOrderFunction close error', error);
            }
        },
    };
}

export default ModalHigherOrderFunction;
